<?php
/*
 * @Author: lokei
 * @Date: 2022-11-16 09:03:59
 * @LastEditors: lokei
 * @LastEditTime: 2022-11-16 11:17:25
 * @Description: 
 */
namespace App\Http\Controllers\Rbac\Auth;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Alipay\EasySDK\Kernel\Factory;
use App\Common\Alipay\Common;
use App\Models\Ucenter\FansModel;
use App\Models\Ucenter\UserModel;
use App\Services\Ucenter\FansService;
use App\Services\Ucenter\UserService;
use Illuminate\Support\Facades\Auth;

class AlipayController extends Controller {
    private UserService $user_service;

    private FansService $fans_service;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->user_service = new UserService();
        $this->fans_service = new FansService();
    }

    public function login(Request $request) {

        Factory::setOptions(Common::getOptions());

        $result = Factory::base()->oauth()->getToken($request->input('code'))->toMap();

        if ($result['user_id'] != null && $result['user_id'] != '') {
            $fans = FansModel::where('openid', '=', $result['user_id'])->where('platform', '=', 'alipay')->first();
            if (!is_null($fans)) {
                if (!($fans->uid > 0)) {
                    $uid = $this->user_service->createUser();
                    $fans->uid = $uid;
                    $fans->save();
                } else {
                    $user = UserModel::where('uid', '=', $fans->uid)->first();
                    if(is_null($user)) {
                        $uid = $this->user_service->createUser();
                        $fans->uid = $uid;
                        $fans->save();
                    }
                }
            } else {
                $fid = $this->fans_service->registerOpenid('alipay', $result['user_id']);
                $fans = FansModel::where('openid', '=', $result['user_id'])->first();
                $uid = $this->user_service->createUser();
                $fans->uid = $uid;
                $fans->save();
            }
            if(!isset($user)) {
                $user = UserModel::where('uid', '=', $fans->uid)->first();
            }
            $token = Auth::login($user);
            $res = ResultTool::success();
            $res['data']['token'] = $token;
            return $res;
        }
        $res = ResultTool::fail();
        $res['errorMsg'] = '小程序用户登入失败！';
        return $res;
    }
}